package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Service

public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.amap.key}")  // 修改为amap
    private String ak;

    @Autowired
    private WebSocketServer webSocketServer;

    private void checkOutOfRange(String address) {
        try {
            // 1. 获取店铺坐标
            String shopLocation = getLocation(shopAddress);

            // 2. 获取用户坐标
            String userLocation = getLocation(address);

            // 3. 计算距离
            int distance = getDistance(shopLocation, userLocation);

            if (distance > 10000) {
                throw new OrderBusinessException("超出配送范围");
            }
        } catch (OrderBusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("配送范围校验异常", e);
            throw new OrderBusinessException("配送范围校验服务异常");
        }
    }

    /**
     * 获取地址的经纬度坐标（高德地理编码API）
     */
    private String getLocation(String address) {
        Map<String, String> params = new HashMap<>();
        params.put("key", ak);
        params.put("address", address);
        params.put("output", "json");

        String response = HttpClientUtil.doGet("https://restapi.amap.com/v3/geocode/geo", params);
        JSONObject json = JSON.parseObject(response);

        // 高德成功状态码是1（百度是0）
        if (!"1".equals(json.getString("status"))) {
            throw new OrderBusinessException("地址解析失败: " + json.getString("info"));
        }

        // 高德返回数据结构不同
        JSONArray geocodes = json.getJSONArray("geocodes");
        if (geocodes == null || geocodes.isEmpty()) {
            throw new OrderBusinessException("地址无匹配结果");
        }

        return geocodes.getJSONObject(0).getString("location"); // 格式: "经度,纬度"
    }

    /**
     * 计算两点间距离（高德距离测量API）
     */
    private int getDistance(String origin, String destination) {
        Map<String, String> params = new HashMap<>();
        params.put("key", ak);
        params.put("origins", origin);
        params.put("destination", destination);

        String response = HttpClientUtil.doGet("https://restapi.amap.com/v3/distance", params);
        JSONObject json = JSON.parseObject(response);

        if (!"1".equals(json.getString("status"))) {
            throw new OrderBusinessException("距离计算失败: " + json.getString("info"));
        }

        JSONArray results = json.getJSONArray("results");
        if (results == null || results.isEmpty()) {
            throw new OrderBusinessException("距离计算无结果");
        }

        return results.getJSONObject(0).getInteger("distance"); // 单位: 米
    }

    /**
     * 智能拼接地址（自动适配直辖市）
     */
    private String buildFullAddress(AddressBook addressBook) {
        List<String> addressParts = new ArrayList<>();

        // 1. 添加省份（所有情况都需要）
        addressParts.add(addressBook.getProvinceName());

        // 2. 处理直辖市特殊情况
        if (!isMunicipality(addressBook.getProvinceName())) {
            // 非直辖市才添加城市名
            addressParts.add(addressBook.getCityName());
        }

        // 3. 添加区和详细地址
        addressParts.add(addressBook.getDistrictName());
        addressParts.add(addressBook.getDetail());

        // 过滤null值并用空格连接
        return addressParts.stream()
                .filter(part -> part != null && !part.isEmpty())
                .collect(Collectors.joining(" "));
    }

    /**
     * 判断是否为直辖市
     */
    private boolean isMunicipality(String province) {
        return province != null && (
                province.endsWith("市") ||  // 中文习惯
                        province.equals("北京") ||
                        province.equals("上海") ||
                        province.equals("天津") ||
                        province.equals("重庆"));
    }


    //用户下单
    //一致性,要么都成功要么都失败，一个方法执行完成之后才会执行
    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        //处理业务异常(收货地址为空,购物车数据为空)
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            //抛出业务异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        String fullAddress = buildFullAddress(addressBook);
        checkOutOfRange(fullAddress);

        //BaseContext.getCurrentId() 之所以能获取到当前用户的 userId，
        // 本质上是因为系统在请求到达业务代码之前（通常通过拦截器、过滤器或AOP）已经解析了前端携带的 Token（如JWT)
        //查询当前购物车数据
        Long userId = BaseContext.getCurrentId();

        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);

        //判断购物车是否为空
        if (shoppingCartList == null && shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向订单表插入1条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook
                .getDetail());
        orders.setUserId(userId);


        orderMapper.insert(orders);

        //把所有的所需要的详细信息一起插入.
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //向订单明细表插入n条数据
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());//设置当前订单明细关联的订单id
            orderDetailList.add(orderDetail);
        }

        orderDetailMapper.insertBatch(orderDetailList);
        //下单成功之后清空用户的购物车数据
        shoppingCartMapper.deleteByUserId(userId);
        //封装vo返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();
        //通过websocket向用户端浏览器推送消息，type orderid content
        Map map=new HashMap();
        map.put("type",1);//1表示来单提醒 2表示客户催单
        map.put("orderId",orders.getId());
        map.put("content","订单号"+orders.getNumber());
        //转换成json字符串
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

        return orderSubmitVO;

    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 用户端订单分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            //查询每个page
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                //把order表的信息拷贝过去了到VO,因为VO继承Orders，就盯着是弄了个新的orders
                BeanUtils.copyProperties(orders, orderVO);
                //然后在设置他的详细信息
                orderVO.setOrderDetailList(orderDetails);
                //最后添加
                list.add(orderVO);

            }
        }

        //想不到
        return new PageResult(page.getTotal(), list);
    }

    @Override
    public OrderVO details(Long id) {
        //获取订单的信息
        OrderVO orders = orderMapper.getById(id);
        Long orderid = orders.getId();
        //获取详细订单的信息
        List<OrderDetail> orderDetail = orderDetailMapper.getByOrderId(orderid);
        //封装成vo然后返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetail);


        return orderVO;
    }

    @Override
    public void cancel(Long id) throws Exception {
        OrderVO orderVO = orderMapper.getById(id);
        if (orderVO == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        //意思大于2 就是错的
        if (orderVO.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(orderVO.getId());
        // 订单处于待接单状态下取消，需要进行退款
        if (orderVO.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
            weChatPayUtil.refund(
                    orderVO.getNumber(), //商户订单号
                    orderVO.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);


    }

    @Override
    //传过来的这个id是order的id,再来一单就是将原订单中的商品重新加入到购物车中,
    // 购物车里面有菜品口味,所以需要查询详细订单
    public void repetition(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();
        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        // 将订单详情对象转换为购物车对象
        //orderDetailList.stream() - 将orderDetailList(订单详情列表)转换为一个Stream流，以便进行函数式操作
        //.map(x -> { ... }) - 对Stream中的每个元素(这里用x表示)进行转换操作
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);


    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        //total（总数）表示满足条件的所有数据总量.records（记录列表）表示当前页的数据集合
        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);
        return new PageResult(page.getTotal(), orderVOList);

    }


    //将原始订单数据 Orders 转换为前端需要的 OrderVO，补充菜品详情。
    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    @Override
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Long orderid = ordersConfirmDTO.getId();
        OrderVO orderVO = orderMapper.getById(orderid);
        orderVO.setStatus(Orders.CONFIRMED);
        orderMapper.update(orderVO);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());
        // 订单等于6已取消的时候不可以取消订单
        if (ordersDB == null || ordersDB.getStatus().equals(Orders.CANCELLED)||ordersDB.getStatus().equals(Orders.REFUND)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }
        // 根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);


    }

    @Override
    public void delivery(Long id) {
        OrderVO orderVO=orderMapper.getById(id);
        // 校验订单是否存在，并且状态为3
        if (orderVO == null || !orderVO.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(orderVO.getId());
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        OrderVO orderVO=orderMapper.getById(id);
        // 校验订单是否存在，并且状态为4
        if (orderVO == null || !orderVO.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(orderVO.getId());
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        orderMapper.update(orders);

    }

    /**
     *
     * @param id
     */
    @Override
    public void remind(Long id) {
        OrderVO orderVO=orderMapper.getById(id);
        // 校验订单是否存在
        if (orderVO == null ) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //通过websocket向用户端浏览器推送消息，type orderid content
        Map map=new HashMap();
        map.put("type",2);//1表示来单提醒 2表示客户催单
        map.put("orderId",id);
        map.put("content","订单号"+orderVO.getNumber());
        //转换成json字符串
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);


    }

}
